package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //0.参数判空
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.获取参数
        Long articleId = dto.getArticleId();
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if(userId==null||userId==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.获取到指定用户的阅读量
        String o = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + articleId, userId.toString());
        if(o!=null){
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(o, ReadBehaviorDto.class);
            Short totalCount = readBehaviorDto.getCount();
            //3.阅读量+1
            Short currentCount = dto.getCount();
            totalCount=(short)(totalCount+currentCount);
            //4.更新阅读量
            dto.setCount(totalCount);
        }
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR+articleId,userId.toString(),dto.getCount().toString());
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
